package fun.boomcat.luckyhe.mirai.plugin.botcontrol.util;

import fun.boomcat.luckyhe.mirai.plugin.botcontrol.pojo.Config;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author Lucky_He
 * @date 2021年8月25日 22:57
 * @description ConfigUtil
 */
public class ConfigUtil {
    private static File configPath;
    private static String configFileName = "config.yml";
    private static Config config;

    public static void init(File path, String configContent) throws IOException {
        configPath = path;

        File[] files = configPath.listFiles();
        boolean hasConfig = false;
        for (File file : files) {
            if (file.getName().equals(configFileName)) {
                hasConfig = true;
                break;
            }
        }

        if (!hasConfig) {
            copyConfigPathFromResource(configContent);
        }

        readConfig();
    }

    private static void readConfig() throws IOException {
        Yaml yaml = new Yaml();
        FileInputStream fis = new FileInputStream(configPath.getPath() + "/" + configFileName);
        config = yaml.loadAs(fis, Config.class);
        fis.close();
    }

    private static void copyConfigPathFromResource(String configContent) throws IOException {
        FileOutputStream fos = new FileOutputStream(configPath.getPath() + "/" + configFileName);

        byte[] buf = configContent.getBytes(StandardCharsets.UTF_8);
        fos.write(buf);
        fos.close();
    }

    public static Config getConfig() throws IOException {
        if (config == null) {
            readConfig();
        }

        return config;
    }

    public static void writeConfig() throws IOException {
        if (config == null) {
            readConfig();
        }

        Yaml yaml = new Yaml();
        FileWriter fw = new FileWriter(configPath.getPath() + "/" + configFileName);
        yaml.dump(config, fw);
        fw.close();
    }
}
